import json
from Interface_DDT.utils.mysql_utils import *

total_data = {
    "testResult": [],
    "testPass": 0,
    "testName": "蜗牛进销存",
    "testAll": 12,
    "testFail": 2,
    "beginTime": 2,
    "totalTime": 2,
    "testSkip": 3,
    "testError": 0
}

case_data = {
    "caseid": "",
    "caseModule": "",
    "testData": "",  # 输入参数
    "description": "",
    "spendTime": 0,
    "status": 0,
    "log": ["无"]
}


# todo  将测试数据 存入数据库
def write_data_to_db(total_data: dict):
    testPass = total_data['testPass']
    testName = total_data['testName']
    testAll = total_data['testAll']
    testFail = total_data['testFail']
    beginTime = total_data['beginTime']
    totalTime = total_data['totalTime']
    testSkip = total_data['testSkip']
    testError = total_data['testError']

    # 新增total
    total_instart_sql = "insert into total_data " \
                        "( testPass, testName, testAll, testFail, beginTime, totalTime, testSkip,testError, create_time, update_time) " \
                        "values('{}','{}','{}','{}','{}','{}','{}','{}',now(),now())" \
        .format(testPass, testName, testAll, testFail, beginTime, totalTime, testSkip, testError)
    instart(total_instart_sql, 'htmlreport')

    # 查到当前数据的主键id
    select_total_id = "select total_id from total_data order by total_id desc limit 0,1"
    id = select(select_total_id, 'htmlreport')
    res_id = id[0][0]
    # 新增case_data
    case_list = total_data["testResult"]
    for i in case_list:
        i['testData'] = i['testData'].replace("'", "\''")
        i['log'] = str(i['log'])
        try:
            i['log'] = i['log'].replace("'", "\''")
        except:
            pass
        case_insert_sql = "insert into case_data (total_id, caseid, caseModule, testData, description, spendTime, status, log, create_time, update_time)" \
                          " values('{}','{}','{}','{}','{}','{}','{}','{}',now(),now())" \
            .format(res_id, i['caseid'], i['caseModule'], i['testData'], i["description"], i["spendTime"], i['status'],
                    i['log'])
        instart(case_insert_sql, 'htmlreport')


# 将数据从数据库取出来
def get_data_from_db():
    # 查询total
    total_data = {"testResult": []}
    select_total_sql = "select total_id,testPass,testName,testAll,testFail,beginTime,totalTime,testSkip,testError " \
                       "from  total_data order by create_time desc limit 0,1"
    res = select(select_total_sql, 'htmlreport')[0]
    res_id = res[0]
    total_data['testPass'] = res[1]
    total_data['testName'] = res[2]
    total_data['testAll'] = res[3]
    total_data['testFail'] = res[4]
    total_data['beginTime'] = str(res[5])
    total_data['totalTime'] = res[6]
    total_data['testSkip'] = res[6]
    total_data['testError'] = res[7]
    # 查询case
    select_total_sql = "select caseid,caseModule,testData,description,spendTime,status,log from case_data where total_id='{}'".format(
        res_id)
    case_res = select(select_total_sql, 'htmlreport')
    case_data = {}
    for i in range(len(case_res)):
        # print(case_res[i])
        case_data['caseid'] = case_res[i][0]
        case_data['caseModule'] = case_res[i][1]
        case_data['testData'] = case_res[i][2]
        case_data['description'] = case_res[i][3]
        case_data['spendTime'] = case_res[i][4]
        case_data['status'] = case_res[i][5]
        case_data['log'] = case_res[i][6]

        total_data['testResult'].append(case_data)
        # print(total_data['testResult'][0])
        case_data = {}
    result = json.dumps(total_data)

    return result


class Report:
    def __init__(self, report_name="接口自动化报告.html"):
        self.report_name = report_name

    def generate_report(self, title, total_data):
        # 写入数据库
        write_data_to_db(total_data)
        # 打开模板 ==读取所有内容
        with open(r"G:\work\Interface_DDT\report\蜗牛进销存v1.3.html", 'r', encoding='utf-8') as fb:
            content = fb.read()
            # 替换标题
            content = content.replace("${title}", title)

            # 替换报告正文
            content = content.replace("${result}", get_data_from_db())

            # 将报告内容 写入 新的文档
            with open(self.report_name, "w", encoding='utf-8') as f:
                f.write(content)


if __name__ == '__main__':
    res = get_data_from_db()
